package com.ada;

import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) throws SQLException {
        System.out.println("Hello World!");
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:app.xml");

        ShardingSphereDataSource obj = (ShardingSphereDataSource) context.getBean("shardingDataSource");

        DataSource ds1 = (DataSource) context.getBean("ds1");


        QueryRunner run = new QueryRunner( obj );
        System.out.println(obj);

        ResultSetHandler<List<Order>> h = new BeanListHandler<Order>(Order.class);


    List<Order> orders= run.query("select * from t_order order by user_id desc limit 10 ", new ResultSetHandler< List<Order>>() {
            @Override
            public  List<Order> handle(ResultSet rs) throws SQLException {

                List<Order> orders = new ArrayList();
                if (!rs.next()) {
                    return orders;
                } else {
                    do {
                        Order order=new Order();
                        order.setStatus(rs.getString("status"));
                        order.setUser(rs.getInt("user_id"));
                        order.setId(rs.getLong("order_id"));
                        orders.add(order);
                    } while(rs.next());
                }

                return orders;
            }
        });
        for (Order order : orders) {
            System.out.println(order);
        }

        try
        {
            for (int i = 1; i < 10; i++) {
                int inserts = run.update( "INSERT INTO t_order (user_id,status) VALUES (?,?)",
                        i,"sdf" );
            }
            // Execute the SQL update statement and return the number of
            // inserts that were made

            // The line before uses varargs and autoboxing to simplify the code
        }
        catch(SQLException sqle) {
            // Handle it
        }

    }
}
